package com.imooc.dao.impl;

import com.imooc.dao.IStudentDao;
import com.imooc.domain.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName StudentDAOSpringJdbcImpl
 * @Description TODO
 * @Author Wxg
 * @Date 2018/11/16 12:12
 * @Version 1.0
 */
public class StudentDAOSpringJdbcImpl implements IStudentDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Student> query() {
        final List<Student> students = new ArrayList<>();
        String sql = "select id, name, age from student";

        jdbcTemplate.query(sql, rs -> {
            Student student = new Student();
            student.setId(rs.getInt("id"));
            student.setName(rs.getString("name"));
            student.setAge(rs.getInt("age"));

            students.add(student);
        });

        return students;
    }

    @Override
    public void save(Student student) {
        String sql = "insert into student (name, age) values(?,?)";

        jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge()});
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
